/*
 * Copyright (C) 2009 CodeWerkz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.codewerkz.prompty;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.codewerkz.util.SettingsLoader;
import com.codewerkz.util.SettingsLoader.LoadSettings;

/**
 * Activity for listing all the presentations in the database.
 * 
 * @author ChaZ
 */
public class PresentationList extends ListActivity implements LoadSettings {
	
	// Database
	private PresentationsDbAdapter mDbHelper;
	private SlidesDbAdapter mSlidesDbHelper;
	
	// Intents 
	private static final int ACTIVITY_SLIDES = 0;
	private static final int ACTIVITY_EDIT = 1;
	private static final int ACTIVITY_CREATE = 2;
	private static final int ACTIVITY_HELP_PRESENTATIONS = 4;
	private static final int ACTIVITY_SETTINGS = 5;
	
	// Context Menu Activities
	private static final int SLIDESHOW_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST +1;
	private static final int DELETE_ID = Menu.FIRST + 2;
	
	// Logging TAG
	//private final String TAG = "Prompty - PresList";
	
	// Settings
	public static SettingsLoader sSettings;
	public static float sFontSizePx;
	public static boolean sWelcomeMessage;
	private static boolean sFirstRun;
	
	/**
	 * Runs this function when the Activity is started.
	 * TODO: XML STRINGS
	 * @return void
	 */
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    // Set up us our layout.
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	    setContentView(R.layout.presentations);
	    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.view_title);
	    
	    // Open new connection to the database.
        mDbHelper = new PresentationsDbAdapter(this);
        mDbHelper.open();
        
        // Fill the layout list and set the list context.
        fillData();
        registerForContextMenu(getListView());
        
	    // Load the settings.
	    loadSettings();
	}
	
	public void loadSettings() {
		// New SettingsLoader object.
		PresentationList.sSettings = new SettingsLoader(this);
		
		// Get the settings.
		sWelcomeMessage = sSettings.isWelcomeMessageEnabled();
		sFontSizePx = sSettings.getFontSize();
		sFirstRun = sSettings.isFirstRun();
		
		// Set up the layout.
		
		// Set up text size
		TextView textView = (TextView) this.findViewById(R.id.presentations_description);
		textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, sFontSizePx);
		
		// Set up welcome message
		if( sWelcomeMessage != true ) {
			ImageView imgLogo = (ImageView) this.findViewById(R.id.presentations_logo);
			TextView txtTitle = (TextView) this.findViewById(R.id.presentations_title);
			TextView txtDesc = (TextView) this.findViewById(R.id.presentations_description);
			
			imgLogo.setVisibility(View.GONE);
			txtTitle.setVisibility(View.GONE);
			txtDesc.setVisibility(View.GONE);
			
			imgLogo = null;
			txtTitle = null;
			txtDesc = null;
		}
		
		// Set up first run
		if( sFirstRun ) {
			sSettings.setFirstRun(false);
			sSettings.savePreferences();
			
			// DO SOMETHING HERE.
		}
		
		// Destroy sSettings.
		sSettings = null;
	}
	
	/**
	 * Runs when the Context Menu is created (Loaded).
	 * 
	 * @return void
	 */
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		// Add in all the menu items.
		menu.setHeaderTitle("Select an action.");
	    menu.add(0, SLIDESHOW_ID, 0, R.string.menu_presentation_slideshow);
		menu.add(0, EDIT_ID, 0, R.string.menu_presentation_edit);
        menu.add(0, DELETE_ID, 0, R.string.menu_presentation_delete);
	}
    
    /**
     * Runs when an item in the Context Menu is selected.
     * 
     * @return boolean
     */
    @Override
	public boolean onContextItemSelected(MenuItem item) {
    	// Get the item selected from the list.
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	
    	// Open a new connection to the Slides Table.
    	mSlidesDbHelper = new SlidesDbAdapter(this);
    	mSlidesDbHelper.open();
    	
    	// Switch in the item ID selected through each case.
		switch(item.getItemId()) {
		
			// If the user pressed the 'Start Slide Show' Button...
			case SLIDESHOW_ID:
				
				// Create a new intent to the Slide Show Activity.
	            Intent i = new Intent (this, SlidesShow.class);
	            
	            // Try to get the ID of the first slide.
	            try {
	            	Cursor firstSlide = mSlidesDbHelper.fetchFirstSlide(info.id);
		            startManagingCursor(firstSlide);
		            i.putExtra("slideID", firstSlide.getLong(firstSlide.getColumnIndex(SlidesDbAdapter.KEY_ROWID)));
	            }
	            // If it fails put a 0 for the slide ID for validation later.
	            catch (Exception e) {
	            	i.putExtra("slideID", 0);
	            }
	            
	            // Put in the presentation ID and close the Adapter to the table. 
				i.putExtra("presID", info.id);
				mSlidesDbHelper.close();
				
				// Start the activity and return true.
				startActivityForResult(i, ACTIVITY_SLIDES);
				return true;
		
			// If the user selected the Delete button...
	    	case DELETE_ID:
	    		
	            // Delete the presentation and then delete all the related slides;
		        mDbHelper.deletePresentation(info.id);
		        mSlidesDbHelper.deleteSlidesFromPresentation(info.id);
		        
		        // Refill the list.
		        fillData();
		        
		        // Close the adapter and return true.
		        mSlidesDbHelper.close();
		        return true;
		        
		    // If the user selects the Edit button.
			case EDIT_ID:
				
				// Start a new intent to the Presentation Edit Activity.
		        Intent j = new Intent(this, PresentationEdit.class);
		        
		        // Put in the Presentation Id.
		        j.putExtra(PresentationsDbAdapter.KEY_ROWID, info.id);
		        
		        // Close the database connection and start the activity.
		        mSlidesDbHelper.close();
		        startActivityForResult(j, ACTIVITY_EDIT);
				return true;
    	}
		
		return super.onContextItemSelected(item);
	}
    
    /**
     * Runs when the Menu button is pressed.
     * 
     * @return boolean
     */
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Create an inflation object and inflate the menu layout.
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.presentation_list_options, menu);
    	return true;
    }
    
    /**
     * Runs when the user selects a button from the Menu.
     * 
     * @return boolean
     */
    public boolean onOptionsItemSelected(MenuItem item) {
    	// Switch all the button.
        switch (item.getItemId()) {
        	// If the new Presentation Button has been pressed.
        	case R.id.presentationList_newPresentation:
        		// Run the create Presentation method.
        		createPresentation();
        		return true;
        	
        	case R.id.presentationList_settings:
        		showSettings();
        		return true;
        	
        	case R.id.presentationList_about:
        		showAbout();
        		return true;
        		
        	case R.id.presentationList_help:
        		showHelp();
        		return true;
        
        }
        return false;
    }
    
    /**
     * Runs when the user clicks on an item in the list.
     * 
     * @return void
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        
        // Create a new intent to the Slides List Activity and add the Presentation ID.
        Intent i = new Intent(this, SlidesList.class);
        i.putExtra(PresentationsDbAdapter.KEY_ROWID, id);
        
        // Start the activity.
        startActivityForResult(i, ACTIVITY_SLIDES);
    }
    
    /**
     * Runs when the Activity is sent a result.
     * 
     * @return void
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        // Switch the result.
        switch ( resultCode ) {
        	case SlidesShow.RESULT_NOSLIDES:
        		// Create a notification because there are no slides.
        		Toast.makeText(PresentationList.this, R.string.slideShow_noSlides,
                        Toast.LENGTH_LONG).show();
        		break;
        }
        
        // On any result, refill the list.
        fillData();
    }
    
    /**
     * Runs when the Activity is ready to be destroyed and collected for Garbage Collection.
     * 
     * @return void
     */
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	
    	// Prevents database leak
    	mDbHelper.close();
    }

    /**
     * Fills up the list with the data from the sqlite3 database.
     * 
     * @return void
     */
    private void fillData() {
        Cursor presCursor = mDbHelper.fetchAllPresentations();
        startManagingCursor(presCursor);
        
        // Create an array to specify the fields we want to display in the list.
        String[] from = new String[]{PresentationsDbAdapter.KEY_NAME, PresentationsDbAdapter.KEY_DESC};
        
        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.presentationTitle, R.id.presentationDesc};
        
        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter pres = 
        		new SimpleCursorAdapter(this, R.layout.presentations_row, presCursor, from, to);
        setListAdapter(pres);
    }
        
    /**
     * Starts the Create Presentation Procedure.
     * 
     * @return void
     */
    private void createPresentation() {
    	// Create a new intent and start the activity to the Presentation Edit Activity.
        Intent i = new Intent(this, PresentationEdit.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }
    
    /**
     * Shows the About screen.
     * 
     * @return void
     */    
    private void showAbout() {
    	Intent i = new Intent(this, About.class);
    	this.startActivity(i);
    }
    
    /**
     * Shows the Help screen.
     * 
     * @return void
     */    
    private void showHelp() {
    	Intent i = new Intent (this, Help.class);
    	i.putExtra("helpPage", 1);
    	this.startActivityForResult(i, ACTIVITY_HELP_PRESENTATIONS);
    }
    
    /**
     * Shows the Help screen.
     * 
     * @return void
     */
    private void showSettings() {
    	Intent i = new Intent (this, Settings.class);
    	this.startActivityForResult(i, ACTIVITY_SETTINGS);
    }
}
